home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-desktop-9.10-i386-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / DistUpgrade / DistUpgradeViewKDE.py < prev    next >
Text File  |  2009-11-02  |  36KB  |  845 lines

  1. # DistUpgradeViewKDE.py 
  2. #  
  3. #  Copyright (c) 2007 Canonical Ltd
  4. #  
  5. #  Author: Jonathan Riddell <jriddell@ubuntu.com>
  6. #  This program is free software; you can redistribute it and/or 
  7. #  modify it under the terms of the GNU General Public License as 
  8. #  published by the Free Software Foundation; either version 2 of the
  9. #  License, or (at your option) any later version.
  10. #  This program is distributed in the hope that it will be useful,
  11. #  but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. #  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. #  GNU General Public License for more details.
  14. #  You should have received a copy of the GNU General Public License
  15. #  along with this program; if not, write to the Free Software
  16. #  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  17. #  USA
  18.  
  19. from PyQt4.QtCore import *
  20. from PyQt4.QtGui import *
  21. from PyQt4 import uic
  22.  
  23. import sys
  24. import logging
  25. import time
  26. import subprocess
  27. import traceback
  28. import tempfile
  29.  
  30. import apt
  31. import apt_pkg
  32. import os
  33. import shutil
  34.  
  35. import pty
  36.  
  37. from DistUpgradeApport import *
  38.  
  39. from DistUpgradeController import DistUpgradeController
  40. from DistUpgradeView import DistUpgradeView, FuzzyTimeToStr, InstallProgress, FetchProgress
  41.  
  42. import select
  43. import gettext
  44. from DistUpgradeGettext import gettext as gett
  45.  
  46. def _(str):
  47.     return unicode(gett(str), 'UTF-8')
  48.  
  49. def utf8(str):
  50.   if isinstance(str, unicode):
  51.       return str
  52.   return unicode(str, 'UTF-8')
  53.  
  54. def loadUi(file, parent):
  55.     if os.path.exists(file):
  56.         uic.loadUi(file, parent)
  57.     else:
  58.         #FIXME find file
  59.         print "error, can't find file: " + file
  60.  
  61. class DumbTerminal(QTextEdit):
  62.     """ A very dumb terminal """
  63.     def __init__(self, installProgress, parent_frame):
  64.         " really dumb terminal with simple editing support "
  65.         QTextEdit.__init__(self, "", parent_frame)
  66.         self.installProgress = installProgress
  67.         self.setFontFamily("Monospace")
  68.         self.setFontPointSize(8)
  69.         self.setWordWrapMode(QTextOption.NoWrap)
  70.         self.setUndoRedoEnabled(False)
  71.         self.setOverwriteMode(True)
  72.         self._block = False
  73.         #self.connect(self, SIGNAL("cursorPositionChanged()"), 
  74.         #             self.onCursorPositionChanged)
  75.  
  76.     def fork(self):
  77.         """pty voodoo"""
  78.         (self.child_pid, self.installProgress.master_fd) = pty.fork()
  79.         if self.child_pid == 0:
  80.             os.environ["TERM"] = "dumb"
  81.         return self.child_pid
  82.  
  83.     def updateInterface(self):
  84.         (rlist, wlist, xlist) = select.select([self.installProgress.master_fd],[],[], 0)
  85.         if len(rlist) > 0:
  86.             line = os.read(self.installProgress.master_fd, 255)
  87.             self.insertWithTermCodes(utf8(line))
  88.         QApplication.processEvents()
  89.  
  90.     def insertWithTermCodes(self, text):
  91.         """ support basic terminal codes """
  92.         display_text = ""
  93.         for c in text:
  94.             # \b - backspace - this seems to comes as "^H" now ??!
  95.             if ord(c) == 8:
  96.                 self.insertPlainText(display_text)
  97.                 self.textCursor().deletePreviousChar()
  98.                 display_text=""
  99.             # \r - is filtered out
  100.             elif c == chr(13):
  101.                 pass
  102.             # \a - bell - ignore for now
  103.             elif c == chr(7):
  104.                 pass
  105.             else:
  106.                 display_text += c
  107.         self.insertPlainText(display_text)
  108.  
  109.     def keyPressEvent(self, ev):
  110.         """ send (ascii) key events to the pty """
  111.         # no master_fd yet
  112.         if not hasattr(self.installProgress, "master_fd"):
  113.             return
  114.         # special handling for backspace
  115.         if ev.key() == Qt.Key_Backspace:
  116.             #print "sent backspace"
  117.             os.write(self.installProgress.master_fd, chr(8))
  118.             return
  119.         # do nothing for events like "shift" 
  120.         if not ev.text():
  121.             return
  122.         # now sent the key event to the termianl as utf-8
  123.         os.write(self.installProgress.master_fd, ev.text().toUtf8())
  124.  
  125.     def onCursorPositionChanged(self):
  126.         """ helper that ensures that the cursor is always at the end """
  127.         if self._block:
  128.             return
  129.         # block signals so that we do not run into a recursion
  130.         self._block = True
  131.         self.moveCursor(QTextCursor.End)
  132.         self._block = False
  133.  
  134. class KDECdromProgressAdapter(apt.progress.CdromProgress):
  135.     """ Report the cdrom add progress """
  136.     def __init__(self, parent):
  137.         self.status = parent.window_main.label_status
  138.         self.progressbar = parent.window_main.progressbar_cache
  139.         self.parent = parent
  140.  
  141.     def update(self, text, step):
  142.         """ update is called regularly so that the gui can be redrawn """
  143.         if text:
  144.           self.status.setText(text)
  145.         self.progressbar.setValue(step/float(self.totalSteps))
  146.         QApplication.processEvents()
  147.  
  148.     def askCdromName(self):
  149.         return (False, "")
  150.  
  151.     def changeCdrom(self):
  152.         return False
  153.  
  154. class KDEOpProgress(apt.progress.OpProgress):
  155.   """ methods on the progress bar """
  156.   def __init__(self, progressbar, progressbar_label):
  157.       self.progressbar = progressbar
  158.       self.progressbar_label = progressbar_label
  159.       #self.progressbar.set_pulse_step(0.01)
  160.       #self.progressbar.pulse()
  161.  
  162.   def update(self, percent):
  163.       #if percent > 99:
  164.       #    self.progressbar.set_fraction(1)
  165.       #else:
  166.       #    self.progressbar.pulse()
  167.       #self.progressbar.set_fraction(percent/100.0)
  168.       self.progressbar.setValue(percent)
  169.       QApplication.processEvents()
  170.  
  171.   def done(self):
  172.       self.progressbar_label.setText("")
  173.  
  174. class KDEFetchProgressAdapter(FetchProgress):
  175.     """ methods for updating the progress bar while fetching packages """
  176.     # FIXME: we really should have some sort of "we are at step"
  177.     # xy in the gui
  178.     # FIXME2: we need to thing about mediaCheck here too
  179.     def __init__(self, parent):
  180.         FetchProgress.__init__(self)
  181.         # if this is set to false the download will cancel
  182.         self.status = parent.window_main.label_status
  183.         self.progress = parent.window_main.progressbar_cache
  184.         self.parent = parent
  185.  
  186.     def mediaChange(self, medium, drive):
  187.       msg = _("Please insert '%s' into the drive '%s'") % (medium,drive)
  188.       change = QMessageBox.question(self.parent.window_main, _("Media Change"), msg, QMessageBox.Ok, QMessageBox.Cancel)
  189.       if change == QMessageBox.Ok:
  190.         return True
  191.       return False
  192.  
  193.     def start(self):
  194.         FetchProgress.start(self)
  195.         #self.progress.show()
  196.         self.progress.setValue(0)
  197.         self.status.show()
  198.  
  199.     def stop(self):
  200.         self.parent.window_main.progress_text.setText("  ")
  201.         self.status.setText(_("Fetching is complete"))
  202.  
  203.     def pulse(self):
  204.         """ we don't have a mainloop in this application, we just call processEvents here and elsewhere"""
  205.         # FIXME: move the status_str and progress_str into python-apt
  206.         # (python-apt need i18n first for this)
  207.         FetchProgress.pulse(self)
  208.         self.progress.setValue(self.percent)
  209.         currentItem = self.currentItems + 1
  210.         if currentItem > self.totalItems:
  211.             currentItem = self.totalItems
  212.  
  213.         if self.currentCPS > 0:
  214.             self.status.setText(_("Fetching file %li of %li at %sB/s") % (currentItem, self.totalItems, apt_pkg.SizeToStr(self.currentCPS)))
  215.             self.parent.window_main.progress_text.setText("<i>" + _("About %s remaining") % unicode(FuzzyTimeToStr(self.eta), 'utf-8') + "</i>")
  216.         else:
  217.             self.status.setText(_("Fetching file %li of %li") % (currentItem, self.totalItems))
  218.             self.parent.window_main.progress_text.setText("  ")
  219.  
  220.         QApplication.processEvents()
  221.         return True
  222.  
  223. class KDEInstallProgressAdapter(InstallProgress):
  224.     """methods for updating the progress bar while installing packages"""
  225.     # timeout with no status change when the terminal is expanded
  226.     # automatically
  227.     TIMEOUT_TERMINAL_ACTIVITY = 240
  228.  
  229.     def __init__(self,parent):
  230.         InstallProgress.__init__(self)
  231.         self._cache = None
  232.         self.label_status = parent.window_main.label_status
  233.         self.progress = parent.window_main.progressbar_cache
  234.         self.progress_text = parent.window_main.progress_text
  235.         self.parent = parent
  236.         try:
  237.             self._terminal_log = open("/var/log/dist-upgrade/term.log","w")
  238.         except Exception, e:
  239.             # if something goes wrong (permission denied etc), use stdout
  240.             logging.error("Can not open terminal log: '%s'" % e)
  241.             self._terminal_log = sys.stdout
  242.         # some options for dpkg to make it die less easily
  243.         apt_pkg.Config.Set("DPkg::StopOnError","False")
  244.  
  245.     def startUpdate(self):
  246.         InstallProgress.startUpdate(self)
  247.         self.finished = False
  248.         # FIXME: add support for the timeout
  249.         # of the terminal (to display something useful then)
  250.         # -> longer term, move this code into python-apt 
  251.         self.label_status.setText(_("Applying changes"))
  252.         self.progress.setValue(0)
  253.         self.progress_text.setText(" ")
  254.         # do a bit of time-keeping
  255.         self.start_time = 0.0
  256.         self.time_ui = 0.0
  257.         self.last_activity = 0.0
  258.         self.parent.window_main.showTerminalButton.setEnabled(True)
  259.  
  260.     def error(self, pkg, errormsg):
  261.         InstallProgress.error(self, pkg, errormsg)
  262.         logging.error("got an error from dpkg for pkg: '%s': '%s'" % (pkg, errormsg))
  263.         # we do not report followup errors from earlier failures
  264.         if gettext.dgettext('dpkg', "dependency problems - leaving unconfigured") in errormsg:
  265.           return False
  266.         summary = _("Could not install '%s'") % pkg
  267.         msg = _("The upgrade will continue but the '%s' package may not "
  268.                 "be in a working state. Please consider submitting a "
  269.                 "bug report about it.") % pkg
  270.         msg = "<big><b>%s</b></big><br />%s" % (summary, msg)
  271.  
  272.         dialogue = QDialog(self.parent.window_main)
  273.         loadUi("dialog_error.ui", dialogue)
  274.         self.parent.translate_widget_children(dialogue)
  275.         dialogue.label_error.setText(utf8(msg))
  276.         if errormsg != None:
  277.             dialogue.textview_error.setText(utf8(errormsg))
  278.             dialogue.textview_error.show()
  279.         else:
  280.             dialogue.textview_error.hide()
  281.         dialogue.connect(dialogue.button_bugreport, SIGNAL("clicked()"), self.parent.reportBug)
  282.         dialogue.exec_()
  283.  
  284.     def conffile(self, current, new):
  285.         """ask question in case conffile has been changed by user"""
  286.         logging.debug("got a conffile-prompt from dpkg for file: '%s'" % current)
  287.         start = time.time()
  288.         prim = _("Replace the customized configuration file\n'%s'?") % current
  289.         sec = _("You will lose any changes you have made to this "
  290.                 "configuration file if you choose to replace it with "
  291.                 "a newer version.")
  292.         markup = "<span weight=\"bold\" size=\"larger\">%s </span> \n\n%s" % (prim, sec)
  293.         self.confDialogue = QDialog(self.parent.window_main)
  294.         loadUi("dialog_conffile.ui", self.confDialogue)
  295.         self.confDialogue.label_conffile.setText(markup)
  296.         self.confDialogue.textview_conffile.hide()
  297.         #FIXME, below to be tested
  298.         #self.confDialogue.resize(self.confDialogue.minimumSizeHint())
  299.         self.confDialogue.connect(self.confDialogue.show_difference_button, SIGNAL("clicked()"), self.showConffile)
  300.  
  301.         # now get the diff
  302.         if os.path.exists("/usr/bin/diff"):
  303.           cmd = ["/usr/bin/diff", "-u", current, new]
  304.           diff = utf8(subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0])
  305.           self.confDialogue.textview_conffile.setText(diff)
  306.         else:
  307.           self.confDialogue.textview_conffile.setText(_("The 'diff' command was not found"))
  308.         result = self.confDialogue.exec_()
  309.         self.time_ui += time.time() - start
  310.         # if replace, send this to the terminal
  311.         if result == QDialog.Accepted:
  312.             os.write(self.master_fd, "y\n")
  313.         else:
  314.             os.write(self.master_fd, "n\n")
  315.  
  316.     def showConffile(self):
  317.         if self.confDialogue.textview_conffile.isVisible():
  318.             self.confDialogue.textview_conffile.hide()
  319.             self.confDialogue.show_difference_button.setText(_("Show Difference >>>"))
  320.         else:
  321.             self.confDialogue.textview_conffile.show()
  322.             self.confDialogue.show_difference_button.setText(_("<<< Hide Difference"))
  323.  
  324.     def fork(self):
  325.         """pty voodoo"""
  326.         (self.child_pid, self.master_fd) = pty.fork()
  327.         if self.child_pid == 0:
  328.             os.environ["TERM"] = "dumb"
  329.             if (not os.environ.has_key("DEBIAN_FRONTEND") or
  330.                 os.environ["DEBIAN_FRONTEND"] == "kde"):
  331.                 os.environ["DEBIAN_FRONTEND"] = "noninteractive"
  332.             os.environ["APT_LISTCHANGES_FRONTEND"] = "none"
  333.         logging.debug(" fork pid is: %s" % self.child_pid)
  334.         return self.child_pid
  335.  
  336.     def statusChange(self, pkg, percent, status):
  337.         """update progress bar and label"""
  338.         # start the timer when the first package changes its status
  339.         if self.start_time == 0.0:
  340.           #print "setting start time to %s" % self.start_time
  341.           self.start_time = time.time()
  342.         self.progress.setValue(self.percent)
  343.         self.label_status.setText(unicode(status.strip(), 'UTF-8'))
  344.         # start showing when we gathered some data
  345.         if percent > 1.0:
  346.           self.last_activity = time.time()
  347.           self.activity_timeout_reported = False
  348.           delta = self.last_activity - self.start_time
  349.           # time wasted in conffile questions (or other ui activity)
  350.           delta -= self.time_ui
  351.           time_per_percent = (float(delta)/percent)
  352.           eta = (100.0 - self.percent) * time_per_percent
  353.           # only show if we have some sensible data (60sec < eta < 2days)
  354.           if eta > 61.0 and eta < (60*60*24*2):
  355.             self.progress_text.setText(_("About %s remaining") % FuzzyTimeToStr(eta))
  356.           else:
  357.             self.progress_text.setText(" ")
  358.  
  359.     def finishUpdate(self):
  360.         self.label_status.setText("")
  361.  
  362.     def updateInterface(self):
  363.         """
  364.         no mainloop in this application, just call processEvents lots here
  365.         it's also important to sleep for a minimum amount of time
  366.         """
  367.         # log the output of dpkg (on the master_fd) to the terminal log
  368.         while True:
  369.             try:
  370.                 (rlist, wlist, xlist) = select.select([self.master_fd],[],[], 0)
  371.                 if len(rlist) > 0:
  372.                     line = os.read(self.master_fd, 255)
  373.                     self._terminal_log.write(line)
  374.                     self.parent.terminal_text.insertWithTermCodes(utf8(line))
  375.                 else:
  376.                     break
  377.             except Exception, e:
  378.                 print e
  379.                 logging.debug("error reading from self.master_fd '%s'" % e)
  380.                 break
  381.  
  382.         # now update the GUI
  383.         try:
  384.           InstallProgress.updateInterface(self)
  385.         except ValueError, e:
  386.           logging.error("got ValueError from InstallProgress.updateInterface. Line was '%s' (%s)" % (self.read, e))
  387.           # reset self.read so that it can continue reading and does not loop
  388.           self.read = ""
  389.         # check about terminal activity
  390.         if self.last_activity > 0 and \
  391.            (self.last_activity + self.TIMEOUT_TERMINAL_ACTIVITY) < time.time():
  392.           if not self.activity_timeout_reported:
  393.             #FIXME bug 95465, I can't recreate this, so here's a hacky fix
  394.             try:
  395.                 logging.warning("no activity on terminal for %s seconds (%s)" % (self.TIMEOUT_TERMINAL_ACTIVITY, self.label_status.text()))
  396.             except UnicodeEncodeError:
  397.                 logging.warning("no activity on terminal for %s seconds" % (self.TIMEOUT_TERMINAL_ACTIVITY))
  398.             self.activity_timeout_reported = True
  399.           self.parent.window_main.konsole_frame.show()
  400.         QApplication.processEvents()
  401.         time.sleep(0.02)
  402.  
  403.     def waitChild(self):
  404.         while True:
  405.             self.updateInterface()
  406.             (pid, res) = os.waitpid(self.child_pid,os.WNOHANG)
  407.             if pid == self.child_pid:
  408.                 break
  409.         # we need the full status here (not just WEXITSTATUS)
  410.         return res
  411.  
  412. # inherit from the class created in window_main.ui
  413. # to add the handler for closing the window
  414. class UpgraderMainWindow(QWidget):
  415.  
  416.     def __init__(self):
  417.         QWidget.__init__(self)
  418.         #uic.loadUi("window_main.ui", self)
  419.         loadUi("window_main.ui", self)
  420.  
  421.     def setParent(self, parentRef):
  422.         self.parent = parentRef
  423.  
  424.     def closeEvent(self, event):
  425.         close = self.parent.on_window_main_delete_event()
  426.         if close:
  427.             event.accept()
  428.         else:
  429.             event.ignore()
  430.  
  431. class DistUpgradeViewKDE(DistUpgradeView):
  432.     """KDE frontend of the distUpgrade tool"""
  433.     def __init__(self, datadir=None, logdir=None):
  434.         # silence the PyQt4 logger
  435.         logger = logging.getLogger("PyQt4")
  436.         logger.setLevel(logging.INFO)
  437.         if not datadir:
  438.           localedir=os.path.join(os.getcwd(),"mo")
  439.         else:
  440.           localedir="/usr/share/locale/update-manager"
  441.  
  442.         # FIXME: i18n must be somewhere relative do this dir
  443.         try:
  444.           gettext.bindtextdomain("update-manager", localedir)
  445.           gettext.textdomain("update-manager")
  446.         except Exception, e:
  447.           logging.warning("Error setting locales (%s)" % e)
  448.  
  449.         #about = KAboutData("adept_manager","Upgrader","0.1","Dist Upgrade Tool for Kubuntu",KAboutData.License_GPL,"(c) 2007 Canonical Ltd",
  450.         #"http://wiki.kubuntu.org/KubuntuUpdateManager", "jriddell@ubuntu.com")
  451.         #about.addAuthor("Jonathan Riddell", None,"jriddell@ubuntu.com")
  452.         #about.addAuthor("Michael Vogt", None,"michael.vogt@ubuntu.com")
  453.         #KCmdLineArgs.init(["./dist-upgrade.py"],about)
  454.  
  455.         # we test for DISPLAY here, QApplication does not throw a 
  456.         # exception when run without DISPLAY but dies instead
  457.         if not "DISPLAY" in os.environ:
  458.             raise Exception, "No DISPLAY in os.environ found"
  459.         self.app = QApplication(["update-manager"])
  460.  
  461.         if os.path.exists("/usr/share/icons/oxygen/48x48/apps/system-software-update.png"):
  462.             messageIcon = QPixmap("/usr/share/icons/oxygen/48x48/apps/system-software-update.png")
  463.         else:
  464.             messageIcon = QPixmap("/usr/share/icons/hicolor/48x48/apps/adept_manager.png")
  465.         self.app.setWindowIcon(QIcon(messageIcon))
  466.  
  467.         self.window_main = UpgraderMainWindow()
  468.         self.window_main.setParent(self)
  469.         self.window_main.show()
  470.  
  471.         self.prev_step = 0 # keep a record of the latest step
  472.  
  473.         self._opCacheProgress = KDEOpProgress(self.window_main.progressbar_cache, self.window_main.progress_text)
  474.         self._fetchProgress = KDEFetchProgressAdapter(self)
  475.         self._cdromProgress = KDECdromProgressAdapter(self)
  476.  
  477.         self._installProgress = KDEInstallProgressAdapter(self)
  478.  
  479.         # reasonable fault handler
  480.         sys.excepthook = self._handleException
  481.  
  482.         self.window_main.showTerminalButton.setEnabled(False)
  483.         self.app.connect(self.window_main.showTerminalButton, SIGNAL("clicked()"), self.showTerminal)
  484.  
  485.         #kdesu requires us to copy the xauthority file before it removes it when Adept is killed
  486.         copyXauth = tempfile.mktemp("", "adept")
  487.         if 'XAUTHORITY' in os.environ and os.environ['XAUTHORITY'] != copyXauth:
  488.             shutil.copy(os.environ['XAUTHORITY'], copyXauth)
  489.             os.environ["XAUTHORITY"] = copyXauth
  490.  
  491.         # Note that with kdesudo this needs --nonewdcop
  492.         ## create a new DCOP-Client:
  493.         #client = DCOPClient()
  494.         ## connect the client to the local DCOP-server:
  495.         #client.attach()
  496.  
  497.         #for qcstring_app in client.registeredApplications():
  498.         #    app = str(qcstring_app)
  499.         #    if app.startswith("adept"): 
  500.         #        adept = DCOPApp(qcstring_app, client)
  501.         #        adeptInterface = adept.object("MainApplication-Interface")
  502.         #        adeptInterface.quit()
  503.  
  504.         # This works just as well
  505.         subprocess.call(["killall", "adept_manager"])
  506.         subprocess.call(["killall", "adept_updater"])
  507.  
  508.         # init gettext
  509.         gettext.bindtextdomain("update-manager",localedir)
  510.         gettext.textdomain("update-manager")
  511.         self.translate_widget_children()
  512.         self.window_main.label_title.setText(self.window_main.label_title.text().replace("Ubuntu", "Kubuntu"))
  513.  
  514.         # setup terminal text in hidden by default spot
  515.         self.window_main.konsole_frame.hide()
  516.         self.konsole_frame_layout = QHBoxLayout(self.window_main.konsole_frame)
  517.         self.window_main.konsole_frame.setMinimumSize(600, 400)
  518.         self.terminal_text = DumbTerminal(self._installProgress, self.window_main.konsole_frame)
  519.         self.konsole_frame_layout.addWidget(self.terminal_text)
  520.         self.terminal_text.show()
  521.  
  522.         # for some reason we need to start the main loop to get everything displayed
  523.         # this app mostly works with processEvents but run main loop briefly to keep it happily displaying all widgets
  524.         QTimer.singleShot(10, self.exitMainLoop)
  525.         self.app.exec_()
  526.  
  527.     def exitMainLoop(self):
  528.         print "exitMainLoop"
  529.         self.app.exit()
  530.  
  531.     def translate_widget_children(self, parentWidget=None):
  532.         if parentWidget == None:
  533.             parentWidget = self.window_main
  534.         if isinstance(parentWidget, QDialog) or isinstance(parentWidget, QWidget):
  535.             if str(parentWidget.windowTitle()) == "Error":
  536.                 parentWidget.setWindowTitle( gettext.dgettext("kdelibs", "Error"))
  537.             else:
  538.                 parentWidget.setWindowTitle(_( str(parentWidget.windowTitle()) ))
  539.  
  540.         if parentWidget.children() != None:
  541.             for widget in parentWidget.children():
  542.                 self.translate_widget(widget)
  543.                 self.translate_widget_children(widget)
  544.  
  545.     def translate_widget(self, widget):
  546.         if isinstance(widget, QLabel) or isinstance(widget, QPushButton):
  547.             if str(widget.text()) == "&Cancel":
  548.                 widget.setText(unicode(gettext.dgettext("kdelibs", "&Cancel"), 'UTF-8'))
  549.             elif str(widget.text()) == "&Close":
  550.                 widget.setText(unicode(gettext.dgettext("kdelibs", "&Close"), 'UTF-8'))
  551.             elif str(widget.text()) != "":
  552.                 widget.setText( _(str(widget.text())).replace("_", "&") )
  553.  
  554.     def _handleException(self, exctype, excvalue, exctb):
  555.         """Crash handler."""
  556.  
  557.         if (issubclass(exctype, KeyboardInterrupt) or
  558.             issubclass(exctype, SystemExit)):
  559.             return
  560.  
  561.         # we handle the exception here, hand it to apport and run the
  562.         # apport gui manually after it because we kill u-m during the upgrade
  563.         # to prevent it from popping up for reboot notifications or FF restart
  564.         # notifications or somesuch
  565.         lines = traceback.format_exception(exctype, excvalue, exctb)
  566.         logging.error("not handled exception in KDE frontend:\n%s" % "\n".join(lines))
  567.         # we can't be sure that apport will run in the middle of a upgrade
  568.         # so we still show a error message here
  569.         apport_crash(exctype, excvalue, exctb)
  570.         if not run_apport():
  571.             tbtext = ''.join(traceback.format_exception(exctype, excvalue, exctb))
  572.             dialog = QDialog(self.window_main)
  573.             loadUi("dialog_error.ui", dialog)
  574.             self.translate_widget_children(self.dialog)
  575.             #FIXME make URL work
  576.             #dialog.connect(dialog.beastie_url, SIGNAL("leftClickedURL(const QString&)"), self.openURL)
  577.             dialog.crash_detail.setText(tbtext)
  578.             dialog.exec_()
  579.         sys.exit(1)
  580.  
  581.     def openURL(self, url):
  582.         """start konqueror"""
  583.         #need to run this else kdesu can't run Konqueror
  584.         #subprocess.call(['su', 'ubuntu', 'xhost', '+localhost'])
  585.         QDesktopServices.openUrl(QUrl(url))
  586.  
  587.     def reportBug(self):
  588.         """start konqueror"""
  589.         #need to run this else kdesu can't run Konqueror
  590.         #subprocess.call(['su', 'ubuntu', 'xhost', '+localhost'])
  591.         QDesktopServices.openUrl(QUrl("https://launchpad.net/ubuntu/+source/update-manager/+filebug"))
  592.  
  593.     def showTerminal(self):
  594.         if self.window_main.konsole_frame.isVisible():
  595.             self.window_main.konsole_frame.hide()
  596.             self.window_main.showTerminalButton.setText(_("Show Terminal >>>"))
  597.         else:
  598.             self.window_main.konsole_frame.show()
  599.             self.window_main.showTerminalButton.setText(_("<<< Hide Terminal"))
  600.         self.window_main.resize(self.window_main.sizeHint())
  601.  
  602.     def getFetchProgress(self):
  603.         return self._fetchProgress
  604.  
  605.     def getInstallProgress(self, cache):
  606.         self._installProgress._cache = cache
  607.         return self._installProgress
  608.  
  609.     def getOpCacheProgress(self):
  610.         return self._opCacheProgress
  611.  
  612.     def getCdromProgress(self):
  613.         return self._cdromProgress
  614.  
  615.     def updateStatus(self, msg):
  616.         self.window_main.label_status.setText(utf8(msg))
  617.  
  618.     def hideStep(self, step):
  619.         image = getattr(self.window_main,"image_step%i" % step)
  620.         label = getattr(self.window_main,"label_step%i" % step)
  621.         image.hide()
  622.         label.hide()
  623.  
  624.     def abort(self):
  625.         step = self.prev_step
  626.         if step > 0:
  627.             image = getattr(self.window_main,"image_step%i" % step)
  628.             if os.path.exists("/usr/share/icons/oxygen/16x16/actions/dialog-cancel.png"):
  629.                 cancelIcon = QPixmap("/usr/share/icons/oxygen/16x16/actions/dialog-cancel.png")
  630.             elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-cancel.png"):
  631.                 cancelIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-cancel.png")
  632.             else:
  633.                 cancelIcon = QPixmap("/usr/share/icons/crystalsvg/16x16/actions/cancel.png")
  634.             image.setPixmap(cancelIcon)
  635.             image.show()
  636.  
  637.     def setStep(self, step):
  638.         if os.path.exists("/usr/share/icons/oxygen/16x16/actions/dialog-ok.png"):
  639.             okIcon = QPixmap("/usr/share/icons/oxygen/16x16/actions/dialog-ok.png")
  640.         elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-ok.png"):
  641.             okIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/16x16/actions/dialog-ok.png")
  642.         else:
  643.             okIcon = QPixmap("/usr/share/icons/crystalsvg/16x16/actions/ok.png")
  644.  
  645.         if os.path.exists("/usr/share/icons/oxygen/16x16/actions/arrow-right.png"):
  646.             arrowIcon = QPixmap("/usr/share/icons/oxygen/16x16/actions/arrow-right.png")
  647.         elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/16x16/actions/arrow-right.png"):
  648.             arrowIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/16x16/actions/arrow-right.png")
  649.         else:
  650.             arrowIcon = QPixmap("/usr/share/icons/crystalsvg/16x16/actions/1rightarrow.png")
  651.  
  652.         if self.prev_step:
  653.             image = getattr(self.window_main,"image_step%i" % self.prev_step)
  654.             label = getattr(self.window_main,"label_step%i" % self.prev_step)
  655.             image.setPixmap(okIcon)
  656.             image.show()
  657.             ##arrow.hide()
  658.         self.prev_step = step
  659.         # show the an arrow for the current step and make the label bold
  660.         image = getattr(self.window_main,"image_step%i" % step)
  661.         label = getattr(self.window_main,"label_step%i" % step)
  662.         image.setPixmap(arrowIcon)
  663.         image.show()
  664.         label.setText("<b>" + label.text() + "</b>")
  665.  
  666.     def information(self, summary, msg, extended_msg=None):
  667.         msg = "<big><b>%s</b></big><br />%s" % (summary,msg)
  668.  
  669.         dialogue = QDialog(self.window_main)
  670.         loadUi("dialog_error.ui", dialogue)
  671.         self.translate_widget_children(dialogue)
  672.         dialogue.label_error.setText(utf8(msg))
  673.         if extended_msg != None:
  674.             dialogue.textview_error.setText(utf8(extended_msg))
  675.             dialogue.textview_error.show()
  676.         else:
  677.             dialogue.textview_error.hide()
  678.         dialogue.button_bugreport.hide()
  679.         dialogue.setWindowTitle(_("Information"))
  680.  
  681.         if os.path.exists("/usr/share/icons/oxygen/48x48/status/dialog-information.png"):
  682.             messageIcon = QPixmap("/usr/share/icons/oxygen/48x48/status/dialog-information.png")
  683.         elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-information.png"):
  684.             messageIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-information.png")
  685.         else:
  686.             messageIcon = QPixmap("/usr/share/icons/crystalsvg/32x32/actions/messagebox_info.png")
  687.         dialogue.image.setPixmap(messageIcon)
  688.         dialogue.exec_()
  689.  
  690.     def error(self, summary, msg, extended_msg=None):
  691.         msg="<big><b>%s</b></big><br />%s" % (summary, msg)
  692.  
  693.         dialogue = QDialog(self.window_main)
  694.         loadUi("dialog_error.ui", dialogue)
  695.         self.translate_widget_children(dialogue)
  696.         dialogue.label_error.setText(utf8(msg))
  697.         if extended_msg != None:
  698.             dialogue.textview_error.setText(utf8(extended_msg))
  699.             dialogue.textview_error.show()
  700.         else:
  701.             dialogue.textview_error.hide()
  702.         dialogue.button_close.show()
  703.         self.app.connect(dialogue.button_bugreport, SIGNAL("clicked()"), self.reportBug)
  704.  
  705.         if os.path.exists("/usr/share/icons/oxygen/48x48/status/dialog-error.png"):
  706.             messageIcon = QPixmap("/usr/share/icons/oxygen/48x48/status/dialog-error.png")
  707.         elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-error.png"):
  708.             messageIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-error.png")
  709.         else:
  710.             messageIcon = QPixmap("/usr/share/icons/crystalsvg/32x32/actions/messagebox_critical.png")
  711.         dialogue.image.setPixmap(messageIcon)
  712.         dialogue.exec_()
  713.  
  714.         return False
  715.  
  716.     def confirmChanges(self, summary, changes, downloadSize, 
  717.                        actions=None, removal_bold=True):
  718.         """show the changes dialogue"""
  719.         # FIXME: add a whitelist here for packages that we expect to be
  720.         # removed (how to calc this automatically?)
  721.         DistUpgradeView.confirmChanges(self, summary, changes, downloadSize)
  722.         msg = unicode(self.confirmChangesMessage, 'UTF-8')
  723.         self.changesDialogue = QDialog(self.window_main)
  724.         loadUi("dialog_changes.ui", self.changesDialogue)
  725.  
  726.         self.changesDialogue.treeview_details.hide()
  727.         self.changesDialogue.connect(self.changesDialogue.show_details_button, SIGNAL("clicked()"), self.showChangesDialogueDetails)
  728.         self.translate_widget_children(self.changesDialogue)
  729.         self.changesDialogue.show_details_button.setText(_("Details") + " >>>")
  730.         self.changesDialogue.resize(self.changesDialogue.sizeHint())
  731.  
  732.         if os.path.exists("/usr/share/icons/oxygen/48x48/status/dialog-warning.png"):
  733.             warningIcon = QPixmap("/usr/share/icons/oxygen/48x48/status/dialog-warning.png")
  734.         elif os.path.exists("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-warning.png"):
  735.             warningIcon = QPixmap("/usr/lib/kde4/share/icons/oxygen/48x48/status/dialog-warning.png")
  736.         else:
  737.             warningIcon = QPixmap("/usr/share/icons/crystalsvg/32x32/actions/messagebox_warning.png")
  738.  
  739.         self.changesDialogue.question_pixmap.setPixmap(warningIcon)
  740.  
  741.         if actions != None:
  742.             cancel = actions[0].replace("_", "")
  743.             self.changesDialogue.button_cancel_changes.setText(cancel)
  744.             confirm = actions[1].replace("_", "")
  745.             self.changesDialogue.button_confirm_changes.setText(confirm)
  746.  
  747.         summaryText = unicode("<big><b>%s</b></big>" % summary, 'UTF-8')
  748.         self.changesDialogue.label_summary.setText(summaryText)
  749.         self.changesDialogue.label_changes.setText(msg)
  750.         # fill in the details
  751.         self.changesDialogue.treeview_details.clear()
  752.         self.changesDialogue.treeview_details.setHeaderLabels(["Packages"])
  753.         self.changesDialogue.treeview_details.header().hide()
  754.         for rm in self.toRemove:
  755.             self.changesDialogue.treeview_details.insertTopLevelItem(0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("Remove %s") % rm]) )
  756.         for inst in self.toInstall:
  757.             self.changesDialogue.treeview_details.insertTopLevelItem(0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("Install %s") % inst]) )
  758.         for up in self.toUpgrade:
  759.             self.changesDialogue.treeview_details.insertTopLevelItem(0, QTreeWidgetItem(self.changesDialogue.treeview_details, [_("Upgrade %s") % up]) )
  760.  
  761.         #FIXME resize label, stop it being shrinkable
  762.         res = self.changesDialogue.exec_()
  763.         if res == QDialog.Accepted:
  764.             return True
  765.         return False
  766.  
  767.     def showChangesDialogueDetails(self):
  768.         if self.changesDialogue.treeview_details.isVisible():
  769.             self.changesDialogue.treeview_details.hide()
  770.             self.changesDialogue.show_details_button.setText(_("Details") + " >>>")
  771.         else:
  772.             self.changesDialogue.treeview_details.show()
  773.             self.changesDialogue.show_details_button.setText("<<< " + _("Details"))
  774.         self.changesDialogue.resize(self.changesDialogue.sizeHint())
  775.  
  776.     def askYesNoQuestion(self, summary, msg, default='No'):
  777.         answer = QMessageBox.question(self.window_main, unicode(summary, 'UTF-8'), unicode("<font>") + unicode(msg, 'UTF-8'), QMessageBox.Yes|QMessageBox.No, QMessageBox.No)
  778.         if answer == QMessageBox.Yes:
  779.             return True
  780.         return False
  781.  
  782.     def confirmRestart(self):
  783.         messageBox = QMessageBox(QMessageBox.Question, _("Restart required"), _("<b><big>Restart the system to complete the upgrade</big></b>"), QMessageBox.NoButton, self.window_main)
  784.         yesButton = messageBox.addButton(QMessageBox.Yes)
  785.         noButton = messageBox.addButton(QMessageBox.No)
  786.         yesButton.setText(_("_Restart Now").replace("_", "&"))
  787.         noButton.setText(gettext.dgettext("kdelibs", "&Close"))
  788.         answer = messageBox.exec_()
  789.         if answer == QMessageBox.Yes:
  790.             return True
  791.         return False
  792.  
  793.     def processEvents(self):
  794.         QApplication.processEvents()
  795.  
  796.     def on_window_main_delete_event(self):
  797.         #FIXME make this user friendly
  798.         text = _("""<b><big>Cancel the running upgrade?</big></b>
  799.  
  800. The system could be in an unusable state if you cancel the upgrade. You are strongly advised to resume the upgrade.""")
  801.         text = text.replace("\n", "<br />")
  802.         cancel = QMessageBox.warning(self.window_main, _("Cancel Upgrade?"), text, QMessageBox.Yes, QMessageBox.No)
  803.         if cancel == QMessageBox.Yes:
  804.             return True
  805.         return False
  806.  
  807. if __name__ == "__main__":
  808.   
  809.   view = DistUpgradeViewKDE()
  810.   view.askYesNoQuestion("input box test","bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar bar ")
  811.  
  812.   if sys.argv[1] == "--test-term":
  813.       pid = view.terminal_text.fork()
  814.       if pid == 0:
  815.           subprocess.call(["bash"])
  816.           sys.exit()
  817.       while True:
  818.           view.terminal_text.updateInterface()
  819.           QApplication.processEvents()
  820.           time.sleep(0.01)
  821.  
  822.   if sys.argv[1] == "--show-in-terminal":
  823.       for c in open(sys.argv[2]).read():
  824.           view.terminal_text.insertWithTermCodes( c )
  825.           #print c, ord(c)
  826.           QApplication.processEvents()
  827.           time.sleep(0.05)
  828.       while True:
  829.           QApplication.processEvents()
  830.  
  831.   cache = apt.Cache()
  832.   for pkg in sys.argv[1:]:
  833.     if cache[pkg].isInstalled and not cache[pkg].isUpgradable: 
  834.       cache[pkg].markDelete(purge=True)
  835.     else:
  836.       cache[pkg].markInstall()
  837.   cache.commit(view._fetchProgress,view._installProgress)
  838.  
  839.   # keep the window open
  840.   while True:
  841.       QApplication.processEvents()
  842.